package com.zc.exceptionhandler;

import com.zc.commonutils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result error(Exception e){
        e.printStackTrace();
        return Result.error().message("执行了全局异常处理");
    }


    //自定义异常处理器
    @ExceptionHandler(ZcException.class)
    public Result error(ZcException e){
        e.printStackTrace();
        return Result.error().code(e.getCode()).message(e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handMethodEX(MethodArgumentNotValidException exception){

        String message = exception.getBindingResult().getFieldErrors().stream().map(s ->
                        "------错误原因：" + s.getDefaultMessage()
        ).collect(Collectors.joining("\n"));
        System.out.println(message);
        return Result.error().message(message);
    }

    @ExceptionHandler(BindException.class)
    public Result bingdEX(BindException exception){
        String message = exception.getFieldErrors().stream().map(s ->
                        "------错误原因：" + s.getDefaultMessage()
        ).collect(Collectors.joining("\n"));
        return Result.error().message(message);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result ConstraintEX(ConstraintViolationException exception){
        String message= exception.getConstraintViolations().stream().
                map(s->s.getPropertyPath()+
                        s.getMessage())
                .collect(Collectors.joining("\t"));
        return Result.error().message(message);
    }


}
